<?php
require "INews.php";
require "IPlugin.php";
//require "Plugin/ClickPlugin.php";

class NewsDetail implements INews
{
    public $newsData;
    public $newsId = 0;
    public $plugs = [];


    public function __construct($newsId)
    {
        $newsFormDataBase = [
            ['news_id'=> 101,'news_title'=>'Android最佳的开源库集锦','news_content'=>'工欲善其事，必先利其器。一个好的开发库可以快速提高开发者的工作效率，甚至让开发工作变得简单。本文收集了大量的Android开发库，快来切磋一下，到底哪一个更适合你？'],
            ['news_id'=> 102,'news_title'=>'Javascript里常见的时间位置属性','news_content' => 'pageX指鼠标在页面上的位置，以页面左侧为参考点clientX指可视区域内离左侧的距离，以滚动条滚动到位置的参考点。各浏览器相同。'],
        ];
        $this->newsId = $newsId;
        $this->newsData = $newsFormDataBase;

        $this->scanPlugins();
        /*$clickPlugin = new ClickPlugin();
        $this->regPlug($clickPlugin);*/
    }
    function scanPlugins()
    {
        //扫描插件
        $scanDir = __DIR__.'/Plugin';
        $dir = dir($scanDir);
        while ($file = $dir->read()){
            if (is_file($scanDir .'/'. $file)){
                $className = basename($file,'.php');
                require $scanDir .'/'. $file;
                $classObject = new $className($this);
                if (is_subclass_of($classObject, 'IPlugin')){
                    $this->regPlug($classObject);//被观察者主动注册
                }
            }
        }
    }
    function getNews()
    {
        foreach ($this->newsData as $newsDatum) {
            if ($newsDatum['news_id'] == $this->newsId){
                return $newsDatum;
            }
        }
    }
    function display()
    {
        $getNews = $this->getNews();
        echo "<h2>".$getNews['news_title']."</h2>";
        echo "<div>".$getNews['news_content']."</div>";
        //执行插件方法
        foreach ($this->plugs as $pluginName => $pluginObject){
            $pluginObject->update($this->newsId);
        }
    }

    function regPlug(IPlugin $plug)
    {
        $this->plugs[strval($plug)] = $plug;
    }

    function removePlug(IPlugin $plug)
    {
        unset($this->plugs[strval($plug)]);
    }
}